package com.lgl.zkclient;

import com.alibaba.fastjson.JSON;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.HashMap;
import java.util.Map;


public class ZkClientTools {

    private static  CuratorFramework client;
    public static final String zkServerAddress = "127.0.0.1:2181";
    public static final String nettyServerAddress = "127.0.0.1";

    /**获取ZooKeeper服务器**/
    public static CuratorFramework getClient() {
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .namespace("server")
                .connectString(zkServerAddress)
                .connectionTimeoutMs(30000)
                .sessionTimeoutMs(50000)
                .retryPolicy(retry)
                .build();
        client.start();

        return client;
    }

    /**
     * 注册服务器节点信息
     * @param ipAddress
     * @param port
     */
    public static void resisterToZookeeper(String path, String ipAddress, int port) throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("ip", ipAddress);
        data.put("port", port);
        byte[] bytes = JSON.toJSONString(data).getBytes();
        Stat stat = ZkClientTools.getClient().checkExists().forPath(path);
        if (stat == null) {
            ZkClientTools.getClient().create().withMode(CreateMode.EPHEMERAL).forPath(path, bytes);
        }
    }
}
